package com.his.server.jdbc;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Map;
import java.util.HashMap;

import org.apache.commons.lang.StringUtils;

import com.his.server.consts.ServerConsts;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;



public class ConnectionHandler implements InvocationHandler {
	
	Connection connect;
	ConnectionPool pool;
	Map <String, Object> statePool = new HashMap <String, Object> ();
	
	public ConnectionHandler (ConnectionPool cpool) {
		this.pool = cpool;
	}
	
	public Connection Bind (Connection conn) {
		
		connect = conn;
		
		Connection proxyconn = (Connection) Proxy.newProxyInstance(
				conn.getClass().getClassLoader(), new Class[]{Connection.class}, this);
		
		return proxyconn;
	}
	
	public Object invoke(Object proxy, Method method, Object aobj[]) throws Throwable {
		
		Object obj = null;
		
		if (StringUtils.equals(method.getName(), ServerConsts.METHOD_CLOSE)) {
			
			pool.releaseConnction(connect);
		} else if (StringUtils.equals(ServerConsts.METHOD_REPARESTATEMENT, method.getName())){
			
			String sqlment = (String) aobj[0];
			
			obj = statePool.get(sqlment);
			
			if (obj == null) {
				
				obj = method.invoke(connect, aobj);
				statePool.put(sqlment, obj);
			}
			
			PreparedStatement pst = (PreparedStatement) obj;
			SQLHandler sqlHandler = new SQLHandler();
			obj = sqlHandler.Bind(pst);
			
		} else {
			obj = method.invoke(connect, aobj);
		}
		
		return obj;
	}
}